package com.ihr360.binlog.config;


import org.flywaydb.core.Flyway;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.jdbc.DataSourceBuilder;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.jdbc.core.JdbcTemplate;

import javax.annotation.PostConstruct;
import javax.sql.DataSource;


/**
 * Created by davidwei on 17-7-20.
 */
@Configuration
public class DataBaseConfig {

    @Bean(name = "dataSource")
    @Primary
    @ConfigurationProperties(prefix = "spring.datasource")
    public DataSource dataSource() {
        DataSource dataSource = DataSourceBuilder.create().build();
        return dataSource;
    }

    @Bean(name = "jdbcTemplate")
    public JdbcTemplate jdbcTemplate(@Qualifier("dataSource") DataSource dataSource) {
        return new JdbcTemplate(dataSource);
    }

    /**
     * 薪资福利数据源
     *
     * @return
     */
    @Bean(name = "payrollDataSource")
    @ConfigurationProperties(prefix = "spring.payroll.datasource")
    public DataSource payrollDataSource() {
        return DataSourceBuilder.create().build();
    }

    @Bean(name = "payrollJdbcTemplate")
    public JdbcTemplate payrollJdbcTemplate(@Qualifier("payrollDataSource") DataSource dataSource) {
        return new JdbcTemplate(dataSource);
    }

    /**
     * 社保公积金
     *
     * @return
     */
    @Bean(name = "sihfDataSource")
    @ConfigurationProperties(prefix = "spring.sihf.datasource")
    public DataSource sihfDataSource() {
        return DataSourceBuilder.create().build();
    }

    @Bean(name = "sihfJdbcTemplate")
    public JdbcTemplate sihfJdbcTemplate(@Qualifier("sihfDataSource") DataSource dataSource) {
        return new JdbcTemplate(dataSource);
    }

    @Value("${flyway.enabled:false}")
    private boolean flywayEnable;

    @Value("${flyway.baseline-on-migrate:false}")
    private boolean flywayBaselineOnMigrate;

    @Value("${flyway.baseline-version:false}")
    private String flywayBaselineVersion;

    @Value("${flyway.locations:classpath:db/migration}")
    private String flywayBaselineLocations;


    @PostConstruct
    public void migrateFlyway() {
        if (flywayEnable) {
            Flyway flyway = new Flyway();
            flyway.setDataSource(dataSource());
            flyway.setBaselineVersionAsString(flywayBaselineVersion);
            flyway.setBaselineOnMigrate(flywayBaselineOnMigrate);
            flyway.setLocations(flywayBaselineLocations);
            flyway.migrate();
        }
    }
}
